<!--
 * @Author: Lizhenyu
 * @Date: 2021-07-22 14:36:53
 * @FilePath: \usp-osm-frondend\src\views\couponsCenter\couponMgmt\couponList.vue
-->
<template>
  <div class="source" v-loading="pageLoading" element-loading-text="加载中...">
    <v-notes>
      <el-form
        label-width="160px"
        :model="couponForm"
        ref="searchForm"
        class="search-form"
        size="small"
      >
        <el-row class="search-row">
          <el-col :span="24">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="券池编号" prop="couponPool">
                  <el-input
                    placeholder="券池编号"
                    v-model="couponForm.couponCode"
                    disabled
                    clearable
                    @keyup.enter.native.prevent="searchService"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="券池名称" prop="couponName">
                  <el-input
                    placeholder="券池名称"
                    v-model="couponForm.couponName"
                    disabled
                    clearable
                    @keyup.enter.native.prevent="searchService"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="券码" prop="couponNo">
                  <el-input
                    placeholder="券码"
                    v-model="couponForm.couponNo"
                    @input="couponForm.couponNo = couponForm.couponNo.replace(/[^\a-\z\A-\Z0-9]/g,'')"
                    clearable
                    @keyup.enter.native.prevent="searchService"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-collapse-transition>
              <div class="filterContent" v-if="showContent">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="状态" prop="couponState">
                      <el-select
                        v-model="couponForm.couponState"
                        placeholder="请选择"
                        popper-class="select-class"
                        :popper-append-to-body="false"
                      >
                        <el-option key label="全部" value></el-option>
                        <el-option
                          v-for="item in lookupItems.COUPONSTATE"
                          :key="item.dicCode"
                          :label="item.dicName"
                          :value="item.dicCode"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="冻结状态" prop="frozenState">
                      <el-select
                        v-model="couponForm.frozenState"
                        placeholder="请选择"
                        popper-class="select-class"
                        :popper-append-to-body="false"
                      >
                        <el-option key label="全部" value></el-option>
                        <el-option
                          v-for="item in lookupItems.FROZENSTATE"
                          :key="item.dicCode"
                          :label="item.dicName"
                          :value="item.dicCode"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="使用有效期">
                      <div class="block">
                        <el-date-picker
                          v-model="couponForm.usePeriodTime"
                          type="daterange"
                          range-separator="至"
                          :default-value="[new Date(), new Date()]"
                          value-format="yyyy-MM-dd"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                        ></el-date-picker>
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="创建时间">
                      <div class="block">
                        <el-date-picker
                          v-model="couponForm.createTime"
                          type="daterange"
                          range-separator="至"
                          :picker-options="pickerOptions"
                          :default-value="[new Date(), new Date()]"
                          value-format="yyyy-MM-dd"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                        ></el-date-picker>
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </el-collapse-transition>
          </el-col>
        </el-row>
        <el-row class="search-row">
          <el-col :span="8" :offset="16" style="text-align: right">
            <el-button
              @click="closeFilter"
              :icon="showContent ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
              class="white-btn filterClose"
            >
              {{ showContent ? '折叠' : '展开' }}
            </el-button>
            <el-button
              @click="resetForm('searchForm')"
              icon="el-icon-refresh-left"
              class="white-btn"
              >重置</el-button
            >
            <el-button
              @click="searchService"
              icon="el-icon-search"
              class="dark-btn search-btn"
              >搜索</el-button
            >
          </el-col>
        </el-row>
        <!-- Filter start -->
      </el-form>
    </v-notes>
    <div class="mb-lg">
      <v-table
        :data="tableData"
        ref="multipleTable"
        :listLoading="listLoading"
        :loadingText="loadingText"
        :paginationTotal="total"
        v-on:pageSizeChange="pageSizeChange"
        v-on:currentPageChange="currentPageChange"
        border
        pagination
        @handleSelectionChange="handleSelectionChange"
      >
        <div slot="header">
          <el-button
            @click="exportCoupon"
            class="dark-btn"
            style="margin-bottom: 0 !important"
            v-if="$auth('ticketCenter:ticketPoolManagement:importTicketCode')"
          >
            导入券码
          </el-button>
          <el-button
            @click="frozen"
            class="dark-btn"
            style="margin-bottom: 0 !important"
            v-if="$auth('ticketCenter:ticketPoolManagement:freezeTicketCode')"
          >
            冻结
          </el-button>
          <el-button
            @click="thaw"
            class="dark-btn"
            style="margin-bottom: 0 !important"
            v-if="$auth('ticketCenter:ticketPoolManagement:thawTicketCode')"
          >
            解冻
          </el-button>
        </div>
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          label="券码"
          align="center"
          prop="couponNo"
          min-width="110"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="状态"
          align="center"
          min-width="110"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ getDictionaryNameByCode('COUPONSTATE', scope.row.couponState) }}
          </template>
        </el-table-column>
        <el-table-column
          label="冻结状态"
          align="center"
          min-width="110"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ getDictionaryNameByCode('FROZENSTATE', scope.row.frozenState) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="usePeriodTime"
          label="使用有效期"
          align="center"
          min-width="130px"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ scope.row.beginUsePeriod | timestampToChange('date') }} 至 {{ scope.row.endUsePeriod | timestampToChange('date') }}
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          align="center"
          min-width="130px"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ scope.row.createTime | timestampToChange('time') }}
          </template>
        </el-table-column>
      </v-table>
    </div>
  </div>
</template>

<script>
import { setRouterParams, getRouterParams } from '@/utils/auth'
import VNotes from '@/components/Notes/index'
import VTable from '@/components/PageTable/index'
import { getCouponCodeList, getCouponDetail, isFrozen } from '@/api/coupon'
import { common } from '@/mixins/common'
import { mapGetters } from 'vuex'
export default {
  name: 'couponList',
  components: {
    VNotes,
    VTable
  },
  mixins: [common],
  data () {
    return {
      id: '',
      tableData: [],
      showContent: false,
      pageLoading: false,
      defaultTime: [new Date(), new Date()],
      statusList: [],
      couponForm: {
        couponCode: '',
        couponName: '',
        couponNo: '',
        couponState: '',
        frozenState: '',
        createTime: [],
        usePeriodTime: [],
        displayStart: 0, // 开始查询条数
        displayLength: 10 // 每页展示条数
      },
      importData: {},
      timeData: {
        createTimeStart: '',
        createTimeEnd: ''
      },
      selectData: [],
      listLoading: false,
      loadingText: '加载中...',
      total: 0,
      pageSize: 10,
      currentPage: 1,
      pickerOptions: {
        disabledDate (time) {
          // 如果没有后面的-8.64e7就是不可以选择今天的
          return time.getTime() > Date.now() // - 8.64e7
        }
      }
    }
  },
  computed: {
    ...mapGetters(['lookupItems', 'roles'])
  },
  created () {
  },
  mounted () {
    let params = {}
    if (this.$route.params.id) {
      setRouterParams(this.$route)
      params = this.$route.params
    } else {
      params = getRouterParams(this.$route)
    }
    this.id = params.id
    this.getDetails(this.id)
  },
  methods: {
    getDetails (id) {
      const params = {
        id: id
      }
      getCouponDetail(params).then((res) => {
        if (res) {
          if (Number(res.code) === 1) {
            this.couponForm.couponCode = res.obj.couponCode
            this.couponForm.couponName = res.obj.couponName
            this.fetchList()
          } else {
            this.$alert('券池信息获取失败')
          }
        }
      })
    },
    searchService () {
      this.couponForm.displayStart = 0
      this.$refs.multipleTable.restPage()
      this.fetchList()
    },
    fetchList () {
      if (
        !this.$auth('ticketCenter:ticketPoolManagement:ticketCodeList')
      ) {
        this.$alert('您没有权限')
        return false
      }
      this.listLoading = true
      const params = {
        ...this.couponForm,
        couponId: getRouterParams(this.$route).id,
        createTimeStart: this.couponForm.createTime ? new Date(this.couponForm.createTime[0] + ' ' + '00:00:00').getTime() : '',
        createTimeEnd: this.couponForm.createTime ? new Date(this.couponForm.createTime[1] + ' ' + '23:59:59').getTime() : '',
        beginUsePeriod: this.couponForm.usePeriodTime ? new Date(this.couponForm.usePeriodTime[0] + ' ' + '00:00:00').getTime() : '',
        endUsePeriod: this.couponForm.usePeriodTime ? new Date(this.couponForm.usePeriodTime[1] + ' ' + '23:59:59').getTime() : ''
      }
      getCouponCodeList(params).then((res) => {
        this.listLoading = false
        if (res) {
          if (Number(res.code) === 1) {
            const obj = res.obj
            this.tableData = obj.data || []
            this.total = obj.total
          } else if (Number(res.code) === 0) {
            this.$confirm(res.msg, {
              confirmButtonText: '确定',
              showCancelButton: false
            })
          } else {
            this.$confirm(this.$t(res.code), {
              confirmButtonText: '确定',
              showCancelButton: false
            })
          }
        }
      })
    },
    resetForm (formName) {
      this.couponForm.couponNo = ''
      this.couponForm.couponState = ''
      this.couponForm.frozenState = ''
      this.couponForm.createTime = ''
      this.couponForm.usePeriodTime = ''
      this.couponForm.displayStart = 0
      this.couponForm.displayLength = 10
      this.searchService()
    },
    pageSizeChange (size) {
      this.couponForm.displayLength = size
      this.fetchList()
    },
    currentPageChange (curPage) {
      this.couponForm.displayStart = curPage - 1
      this.fetchList()
    },
    handleSelectionChange (val) {
      this.selectData = val
    },
    exportCoupon () {
      this.$router.push({ name: 'fileImport', params: { id: this.id } })
    },
    isAllEqual (array) {
      if (array.length > 0) {
        return !array.some(function (value, index) {
          return value !== array[0]
        })
      } else {
        return true
      }
    },
    frozen () {
      let tipsFlag
      const idList = []
      const statusList = []
      if (this.selectData.length === 0) {
        return false
      }
      this.selectData.forEach(item => {
        idList.push(item.id)
        statusList.push(item.frozenState)
      })
      if (this.isAllEqual(statusList)) {
        statusList.forEach(item => {
          if (item === '1') {
            tipsFlag = true
          } else {
            tipsFlag = false
          }
        })
      } else {
        tipsFlag = false
      }
      const params = {
        ids: idList,
        frozenState: tipsFlag ? '2' : '1'
      }
      this.$alert(`${tipsFlag ? '是否冻结所选券码' : '所选券码包含冻结状态，请重新选择'}`, '冻结', {
        confirmButtonText: '确定',
        cancelButtonText: '关闭',
        showCancelButton: true,
        showConfirmButton: tipsFlag,
        callback: action => {
          if (action === 'confirm') {
            isFrozen(params).then(res => {
              if (res) {
                this.listLoading = false
                if (Number(res.code) === 1) {
                  this.$alert('操作成功')
                  this.fetchList()
                } else {
                  this.$alert('操作失败')
                  this.fetchList()
                }
              }
            })
          } else {
          }
        }
      })
    },
    thaw () {
      let tipsFlag
      const idList = []
      const statusList = []
      if (this.selectData.length === 0) {
        return false
      }
      this.selectData.forEach(item => {
        idList.push(item.id)
        statusList.push(item.frozenState)
      })
      if (this.isAllEqual(statusList)) {
        statusList.forEach(item => {
          if (item === '2') {
            tipsFlag = true
          } else {
            tipsFlag = false
          }
        })
      } else {
        tipsFlag = false
      }
      const params = {
        ids: idList,
        frozenState: tipsFlag ? '1' : '2'
      }
      this.$alert(`${tipsFlag ? '是否解冻所选券码' : '所选券码包含正常状态，请重新选择'}`, '解冻', {
        confirmButtonText: '确定',
        cancelButtonText: '关闭',
        showCancelButton: true,
        showConfirmButton: tipsFlag,
        callback: action => {
          if (action === 'confirm') {
            isFrozen(params).then(res => {
              if (res) {
                this.listLoading = false
                if (Number(res.code) === 1) {
                  this.$alert('操作成功')
                  this.fetchList()
                } else {
                  this.$alert('操作失败')
                  this.fetchList()
                }
              }
            })
          } else {
          }
        }
      })
    },
    closeFilter () {
      this.showContent = !this.showContent
    }
  }
}
</script>

<style>
</style>
